<template>
	<view class="container" style="height: 100%;width: 100%;">
	
		
		<view class="card-container">
			<view class="card">
				<view class="card-title">支付卡</view>
			</view>
			<view class="icon-container">
				<u-icon label="将手机背部靠近刷卡区" space="12rpx" labelPos="bottom" size="140rpx" :name="shuaka"></u-icon>
				<p>{{cardNumber}}</p>

			</view>
		</view>
	</view>
</template>

<script>
	import Config from '@/util/index.js'
	// #ifdef APP-PLUS
	import nfc from '../../../../js_sdk/cjn-nfc-tool/Android-App-NFC/tool.js'
	// #endif
	//import * as nfc from "@/uni_modules/nfc-uts";
	import {
		bindCard
	} from '../../../../api/user';
	import {
		number
	} from 'mathjs';
	// #ifdef MP-WEIXIN
	const nfcAdapter = wx.getNFCAdapter();
	// #endif
	export default {
		data() {
			return {
				cardNumber: "",
				shuaka: '',
				nfcadapter: null
			}
		},
		created() {
			this.shuaka = this.picUrl + "shuaka.png"
		},
		onShow() {
			uni.getStorage({
				key: 'userifo',
				success: (res) => {
					const userInfo = JSON.parse(res.data);
					this.userId = userInfo.userId;
				}
			});


			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform;

			// uni.showModal({
			// 	title: "调试",
			// 	content: platform,
			// 	confirmText: '确认',
			// 	success(res) {

			// 	}
			// })
			// #ifdef APP-PLUS
			//平台特有的API实现
			if (platform === 'android') {
				let _this = this;
				nfc.nfcGetId({
					success: function(data) {
						console.log(data)
						const num = parseInt(data, 16)
						_this.cardNumber = num.toString(10)
						uni.showModal({
							title: '提示',
							content: "是否绑定卡号为" + _this.cardNumber + "的卡片为支付卡？",
							confirmText: '确认',
							success: function(res) {
								if (res.confirm) {
									//	that.readCard()
									console.log('用户点击继续！');
								} else if (res.cancel) {
									console.log('用户点击取消！');
								}
							}
						});

					},
					fail: function(err) {
						uni.showModal({
							title: '提示',
							content: err,
							confirmText: '确认',
							success: function(res) {
								if (res.confirm) {
									//	that.readCard()
									console.log('用户点击继续！');
								}
							}
						});
					},
					complete: function() {

					}
				});
			}
			// #endif
			// #ifdef MP-WEIXIN

			// 获取NFC适配器实例


			// 定义常量
			const DEFAULT_KEY = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
			const AUTH_COMMAND_CODE = 0x61;
			const BLOCK_NUMBER = 0x0b;
			let that = this;
			// 监听NFC标签被发现的事件
			nfcAdapter.onDiscovered(res => {

				console.log("读取到卡片了", res);
				const tagId = new Uint8Array(res.id); // 将ArrayBuffer转换为Uint8Array
				const tagIdString = Array.from(tagId).map(byte => byte.toString(16).padStart(2, '0'))
					.join(''); // 将tagId转换为字符串，不使用:拼接
				let number = parseInt(tagIdString, 16).toString(10); //3983487595
				console.log("卡片ID (16进制字符串):", tagIdString); // 打印卡片ID的字符串形式
				console.log("卡片ID (10进制字符串):", number); // 打印卡片ID的字符串形式
				handleTagDiscovered(tagId, number);
			})

			// 启动NFC发现
			nfcAdapter.startDiscovery({
				success(res) {
					console.log("NFC发现启动成功", res);
				},
				fail(err) {
					console.error("启动NFC发现失败", err);
					wx.showToast({
						title: '启动NFC发现失败!',
						icon: 'none'
					});
				}
			});

			// 处理NFC标签发现事件
			function handleTagDiscovered(tagId, number) {
				// 获取MifareClassic实例
				const mifare = nfcAdapter.getMifareClassic();

				// 连接到NFC标签
				mifare.connect({
					success(res) {
						console.log('连接成功', res);
						// authenticateTag(mifare, tagId, number);
						uni.showModal({
							title: '提示',
							content: "是否绑定卡号为" + number + "的卡片为支付卡？",
							confirmText: '确认',
							success: function(res) {
								if (res.confirm) {
									that.submit(number);
									//	that.readCard()
									//console.log('用户点击继续！');
								} else if (res.cancel) {
									//console.log('用户点击取消！');
								}
							}
						});
					},
					fail(err) {
						console.error('连接失败', err);
						wx.showToast({
							title: '连接失败!',
							icon: 'none'
						});
					}
				});
			}

			// 认证NFC标签
			function authenticateTag(mifare, tagId, carNumber) {
			
				var arr = [0x61, 0x04, 0x11, 0x22, 0x33, 0x44, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
				var arrayBuffer = new Uint8Array(arr).buffer
				// const authCommand = new Uint8Array([
				//   AUTH_COMMAND_CODE, // 认证 A 密钥命令
				//   BLOCK_NUMBER, // 块区编号
				//   ..tagId, // 4位卡片UID
				//   ..DEFAULT_KEY // 6位卡片密钥
				// ]);

				// 进行认证
				// mifare.transceive({
				// 	data: arrayBuffer,
				// 	success(authRes) {

				// 		console.log('认证成功', authRes);
				// 		const rrrr = new Uint8Array(authRes.data); // 将ArrayBuffer转换为Uint8Array
				// 		const result = Array.from(rrrr).map(byte => byte.toString(16).padStart(2, '0'))
				// 			.join(''); // 将tagId转换为字符串，不使用:拼接
				// 		console.log(result)
				// 		uni.showModal({
				// 			title: '提示',
				// 			content: "是否绑定卡号为" + carNumber + "的卡片为支付卡？",
				// 			confirmText: '确认',
				// 			success: function(res) {
				// 				if (res.confirm) {
				// 					that.submit(carNumber);
				// 					//	that.readCard()
				// 					//console.log('用户点击继续！');
				// 				} else if (res.cancel) {
				// 					//console.log('用户点击取消！');
				// 				}
				// 			}
				// 		});

				// 	},
				// 	fail(err) {
				// 		console.error('认证失败', err);
				// 		wx.showToast({
				// 			title: '认证失败!',
				// 			icon: 'none'
				// 		});
				// 	}
				// });
			}

			// #endif
			// let that=this;
			// nfc.gotoDemoActivity(function(result){
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: result.message,
			// 		confirmText:'继续',
			// 		success: function (res) {
			// 			if (res.confirm) {
			// 				that.readCard()
			// 				console.log('用户点击继续！');
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消！');
			// 			}
			// 		}
			// 	});
			// 	 const num = parseInt(	that.cardNumber.message, 16)
			// 	that.cardNumber=num.toString(10)
			// 	console.log('NFC',result);
			// });



		},
		methods: {

			// readCard(){
			// 	let that=this;
			// 	nfc.gotoDemoActivity(function(result){
			// 	    uni.showModal({
			// 	        title: '提示',
			// 	        content: result.message,
			// 	        confirmText:'继续',
			// 	        success: function (res) {
			// 	            if (res.confirm) {

			// 	                console.log('用户点击继续！');
			// 	            } else if (res.cancel) {
			// 	                console.log('用户点击取消！');
			// 	            }
			// 	        }
			// 	    });

			// 	    console.log('NFC',result);
			// 	});
			// },
			submit(cardNumber) {

				bindCard({
					userId: this.userId,
					cardNum: cardNumber
				}).catch(res1 => {

					if (res1.data.code == 200) {

						uni.showModal({
							showCancel: false,
							content: "绑定成功，请妥善管理卡片",
							success() {
								uni.navigateBack({
									delta: 1
								})
							}
						})
						console.log(res1.data)

					} else {
						uni.showModal({
							showCancel: false,
							content: res1.data.msg,
							success() {
								// uni.navigateBack({
								// 	delta: 1
								// })
							}
						})
					}
				})

			},
		},
		onHide() {
			// #ifdef APP-PLUS
			plus.globalEvent.removeEventListener('newintent', function() {
				//console.log('remove newintent');
			});
			plus.globalEvent.removeEventListener('pause', function(e) {
				//console.log('remove pause');
			});
			plus.globalEvent.removeEventListener('resume', function(e) {
				//console.log('remove resume');
			});
			// #endif
			// #ifdef MP-WEIXIN
			if (nfcAdapter) {
				nfcAdapter.stopDiscovery()
			}
			// #endif
		},
		// 销毁监听事件 避免重新进入页面重复读卡
		beforeDestroy() {
			// #ifdef APP-PLUS 
			plus.globalEvent.removeEventListener('newintent', function() {
				//console.log('remove newintent');
			});
			plus.globalEvent.removeEventListener('pause', function(e) {
				//console.log('remove pause');
			});
			plus.globalEvent.removeEventListener('resume', function(e) {
				//console.log('remove resume');
			});
			// #endif
			// #ifdef MP-WEIXIN
			if (nfcAdapter) {
				nfcAdapter.stopDiscovery()
			}
			// #endif
		}
	}
</script>
<style lang="scss">
	.container {
		height: 100%;
	}

	.card-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		flex: 1;
		/* 确保 card-container 占据剩余空间 */
	}

	.card {
		background-color: green;
		width: calc(100% - 4rem);
		height: 12rem;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 2rem;
		box-sizing: border-box;
		border-radius: 1rem;
	}

	.card-title {
		align-self: flex-start;
		margin: 1rem;
		color: white;
	}

	.icon-container {
		display: flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		/* 确保 icon-container 占据剩余空间 */
	}
</style>